from flask import Blueprint, make_response

from query.blog_query import add_one_blog, find_count, find_like_count, pagination_query, find_is_like, find_one_blog, find_class_related_blog, drop_like, del_drop_like, update_like_number
from utils.index import request_get, return_format
from utils.utils import return_model

blog = Blueprint('blog', __name__)


@blog.route("/add_blog", methods=['POST'])
def add_blog():
    select_label = request_get("select_label")
    blog_info = {
        "label": request_get("title"),
        "abstract": request_get("abstract"),
        "blog": request_get("content"),
        "storage_time": request_get("storage_time"),
        "year": request_get("year"),
        "month": request_get("month"),
        "day": request_get("day"),
        "like_number": 0
    }
    add_one_data = add_one_blog(blog_info, select_label)
    if add_one_data["msg"] == "success":
        return make_response((return_format("博客添加成功!", None, 200)))
    elif add_one_data["msg"] == "error":
        return make_response((return_format("博客添加失败!", None, 500)))


@blog.route("/paging", methods=['POST'])
def paging():
    # 首先判断当前用户是搜索状态，
    str_part = request_get("str_part")
    page_number = request_get("page_number")
    page_size = request_get("page_size")
    admin_id = request_get("id")
    if str_part == "":
        # 如果当字符串是空，则代表当前用户是在浏览主页，即没有搜索状态
        count = find_count()
    else:
        count = find_like_count(str_part)
    if count["msg"] == "error":
        return make_response((return_format("查询博客总数失败!", {"count": 0}, 500)))
    if count["msg"] == "success" and count["data"] == 0:
        return make_response((return_format("未查询到数据!", {"count": count["data"], "blog_list": [], "blog_id_dict": [], "page_number": 1, "page_size": page_size}, 200)))
    blog_data = pagination_query(str_part, page_number, page_size)
    if blog_data["msg"] == "error":
        return make_response((return_format("查询博客失败!", {"count": 0}, 500)))
    if blog_data["msg"] == "success":
        # 如果返回成功则首先获取到当前查询到的blog_id,并且存放到列表中
        # 查询链接表，返回一个字典，并记录当前用户是否点赞过这篇博客
        # 存放当前查询出的博客的id信息
        blog_id_list = []
        # 存放当前查询出的博客
        blog_list = []
        for item in blog_data["data"]:
            blog_info = item.blog_to_dict()
            blog_info["class_list"] = []
            for index in item.blog_class_list:
                blog_info["class_list"].append(index.class_to_dict())
            blog_list.append(blog_info)
            blog_id_list.append(blog_info["id"])
        # 创建一个字典，键是blog_id，值初始化为False
        blog_id_dict = {item: False for item in blog_id_list}
        # 如果admin_id为空则代表该用户未登录
        # 未登录状态下默认所有博客均未点赞
        if admin_id is None:
            return make_response((return_format("查询博客成功!", {"count": count["data"], "blog_list": return_model(blog_list, ["abstract", "class_list", "id", "label", "like_number", "storage_time", ]), "blog_id_dict": blog_id_dict, "page_number": page_number, "page_size": page_size}, 200)))
        else:
            # 如果admin_id存在则代表用户已经登录
            # 执行查询并获取结果（只获取blog_id列）
            is_like_data = find_is_like(admin_id, blog_id_list)
            blog_ids_found = set(result.blog_id for result in is_like_data["data"])
            # 更新字典中存在的blog_id为True
            for blog_id in blog_ids_found:
                blog_id_dict[blog_id] = True
            return make_response((return_format("查询博客成功!", {"count": count["data"], "blog_list": return_model(blog_list, ["abstract", "class_list", "id", "label", "like_number", "storage_time", ]), "blog_id_dict": blog_id_dict, "page_number": page_number, "page_size": page_size}, 200)))


@blog.route("/get_count", methods=['POST'])
def get_count():
    count = find_count()
    if count["msg"] == "error":
        return make_response((return_format("查询博客总数失败!", {"count": 0}, 500)))
    if count["msg"] == "success":
        return make_response((return_format("查询博客总数成功!", {"count": count["data"]}, 200)))


@blog.route("/get_blog", methods=['POST'])
def get_blog():
    blog_id = request_get("id")
    find_one_data = find_one_blog({"id": blog_id})
    if find_one_data["msg"] == "error":
        return make_response((return_format("查询博客失败!", None, 500)))
    if find_one_data["msg"] == "success":
        blog_info = find_one_data["data"].blog_to_dict()
        return make_response((return_format("查询博客成功!", blog_info, 200)))


@blog.route("/get_class_related_blog", methods=['POST'])
def get_class_related_blog():
    # class_id: class_id.value,
    # limit: offset.limit,
    # offset: offset.offset,
    # id: store.user_info.user_id
    class_id = request_get("class_id")
    limit = request_get("limit")
    offset = request_get("offset")
    admin_id = request_get("id")
    blog_data = find_class_related_blog(class_id, limit, offset)
    if blog_data["msg"] == "error":
        return make_response((return_format("查询博客失败!", None, 500)))
    if blog_data["msg"] == "success":
        # 如果返回成功则首先获取到当前查询到的blog_id,并且存放到列表中
        # 查询链接表，返回一个字典，并记录当前用户是否点赞过这篇博客
        # 存放当前查询出的博客的id信息
        blog_id_list = []
        # 存放当前查询出的博客
        blog_list = []
        for item in blog_data["data"]:
            blog_info = item.blog_to_dict()
            blog_info["class_list"] = []
            for index in item.blog_class_list:
                blog_info["class_list"].append(index.class_to_dict())
            blog_list.append(blog_info)
            blog_id_list.append(blog_info["id"])
        # 创建一个字典，键是blog_id，值初始化为False
        blog_id_dict = {item: False for item in blog_id_list}
        # 如果admin_id为空则代表该用户未登录
        # 未登录状态下默认所有博客均未点赞
        if admin_id is None:
            return make_response((return_format("查询博客成功!", {"blog_list": return_model(blog_list, ["abstract", "class_list", "id", "label", "like_number", "storage_time", ]), "blog_id_dict": blog_id_dict}, 200)))
        else:
            # 如果admin_id存在则代表用户已经登录
            # 执行查询并获取结果（只获取blog_id列）
            is_like_data = find_is_like(admin_id, blog_id_list)
            blog_ids_found = set(result.blog_id for result in is_like_data["data"])
            # 更新字典中存在的blog_id为True
            for blog_id in blog_ids_found:
                blog_id_dict[blog_id] = True
            return make_response((return_format("查询博客成功!", {"blog_list": return_model(blog_list, ["abstract", "class_list", "id", "label", "like_number", "storage_time", ]), "blog_id_dict": blog_id_dict}, 200)))


@blog.route("/add_drop_like", methods=['POST'])
def add_drop_like():
    admin_id = request_get("admin_id")
    blog_id = request_get("blog_id")
    data = drop_like(admin_id, blog_id)
    if data["msg"] == "success":
        update_like_number(blog_id, "+")
        return make_response((return_format("点赞成功!", None, 200)))
    if data["msg"] == "error":
        return make_response((return_format("点赞失败!", None, 500)))


@blog.route("/delete_drop_like", methods=['POST'])
def delete_drop_like():
    admin_id = request_get("admin_id")
    blog_id = request_get("blog_id")
    data = del_drop_like(admin_id, blog_id)
    if data["msg"] == "success":
        update_like_number(blog_id, "-")
        return make_response((return_format("取消点赞成功!", None, 200)))
    if data["msg"] == "error":
        return make_response((return_format("取消点赞失败!", None, 500)))
